package com.woniuxy.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.dto.PageDto;
import com.woniuxy.entity.Address;
import com.woniuxy.entity.Log;
import com.woniuxy.entity.Orders;
import com.woniuxy.entity.Product;
import com.woniuxy.entity.User;
import com.woniuxy.mapper.AddressMapper;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.mapper.OrdersMapper;
import com.woniuxy.mapper.ProductMapper;
import com.woniuxy.rabbitMQ.CancelOrderSender;
import com.woniuxy.service.AddressService;
import com.woniuxy.service.LogService;
import com.woniuxy.service.OrdersService;
import com.woniuxy.service.UserService;
import com.woniuxy.utils.EmailUtil;
import com.woniuxy.utils.OrderUtil;

import lombok.Data;

@Data
@Service
public class OrdersServiceImpl implements OrdersService {

	@Autowired
	private OrdersMapper ordersMapper;

	@Autowired
	private LogService logService;

	@Autowired
	private UserService userService;

	@Autowired
	private AddressService addressService;

	@Autowired
	private CancelOrderSender cancelOrderSender; // 延时取消订单
	
	@Autowired
	private OrderMapper orderMapper; 
	@Autowired
	private AddressMapper addressMapper;
	@Autowired
	private ProductMapper productMapper;
	@Autowired 
	LogService logservice;

	@Override
	public int updataStatus(String order_no, int status) {

		return ordersMapper.updataStatus(order_no, status);
	}

	@Override
	public Boolean updataOrder(Orders order) {

		logService.addLog(order.getU_id(), "修改", "订单id" + order.getO_id(), new Date());

		return ordersMapper.updataOrder(order) > 0;
	}

	@Override
	public Boolean delOrders(int o_id, int u_id) {
		int result = ordersMapper.delOrders(o_id);

		logService.addLog(u_id, "删除", "订单id" + o_id, new Date());

		return ordersMapper.delOrders(o_id) > 0;
	}

	@Override
	public Boolean addOrders(int p_id, int u_id, BigDecimal auction, BigDecimal service_charge,
			BigDecimal total_money) {

		String order_no = OrderUtil.generateOrderNo();
		User user = userService.findUserByUid(u_id);
		Address address = addressService.findAddressByUidY(u_id);
		String receiver_address = address.getProvince() + " " + address.getCity() + " " + address.getCounty() + " "
				+ address.getDetailed();

		Orders order = new Orders().setP_id(p_id).setU_id(u_id).setOrder_no(order_no).setOrder_date(new Date())
				.setService_charge(service_charge).setTotal_money(total_money).setConsignee(address.getAccept())
				.setReceiver_address(receiver_address).setPhone(address.getTelphone()).setStatus(0);

		// 添加延时订单
		sendDelayMessageCancelOrder(order_no);

		return ordersMapper.addOrders(order) > 0;
	}

	@Override
	public int updataTime(int o_id) {

		return ordersMapper.updataTime(o_id, new Date());
	}

	@Override
	public PageInfo<Orders> findOrdersByUid(int u_id, int pageNum, int pageSize) {

		PageHelper.startPage(pageNum, pageSize);
		List<Orders> list = ordersMapper.findOrdersByUid(u_id);
		PageInfo<Orders> page = new PageInfo<Orders>(list);

		return page;
	}

	@Override
	public PageInfo<Orders> findOrdersByStatus(int status, int pageNum, int pageSize) {

		PageHelper.startPage(pageNum, pageSize);
		List<Orders> list = ordersMapper.findOrdersByStatus(status);
		PageInfo<Orders> page = new PageInfo<Orders>(list);

//		System.out.println("总数量：" + page.getTotal());
//		System.out.println("当前页查询记录：" + page.getList().size());
//		System.out.println("当前页码：" + page.getPageNum());
//		System.out.println("每页显示数量：" + page.getPageSize());
//		System.out.println("总页：" + page.getPages());

		return page;
	}

	@Override
	public Orders findOrdersByOn(String order_no) {

		return ordersMapper.findOrdersByOn(order_no);
	}

	@Override
	public Boolean passed(String order_no, int u_id) {
		// 获取email
		String email = userService.findUserByUid(u_id).getEmail();
		// 订单流拍状态
		updataStatus(order_no, 10);

		// 异步处理发送邮件，避免异常
		new Thread(new Runnable() {
			@Override
			public void run() {
				EmailUtil.send(email, order_no);
			}
		}).start();
		return true;
	}

	@Override
	public BigDecimal findYesterday() {

		List<Orders> list = ordersMapper.findYesterday();
		return MoneySum(list);
	}

	@Override
	public BigDecimal findSomeday(Date time) {
		List<Orders> list = ordersMapper.findSomeday(time);

		return MoneySum(list);
	}

	@Override
	public BigDecimal findTimeFrame(Date max_time, Date min_time) {
		List<Orders> list = ordersMapper.findTimeFrame(max_time, min_time);

		return MoneySum(list);
	}

	// 订单超时时间，假设为10分钟 10 * 30 * 1000
	private Long DELAY_TIME = 300000L;

	// 发送延迟消息
	private void sendDelayMessageCancelOrder(String order_no) {

		cancelOrderSender.sendMessage(order_no, DELAY_TIME);
	}

	// 遍历求交易额
	private BigDecimal MoneySum(List<Orders> list) {
		BigDecimal money = new BigDecimal(0);
		for (Orders orders : list) {
			if (orders.getTotal_money() != null) {
				money = money.add(orders.getTotal_money());
			}
		}
		return money;
	}

	@Override
	public PageDto<Orders> find(int uid,int page) {
		PageHelper.startPage(page,7);
		List<Orders> orders = orderMapper.find(uid);
		PageInfo<Orders> pageInfo = new PageInfo<>(orders);
		PageDto<Orders> pageDto = new PageDto<Orders>();
		pageDto.setCurrentPage(page);//当前页
		pageDto.setPageSize(7);//每一页大小
		pageDto.setTotal(pageInfo.getTotal());//总条数
		pageDto.setTotalPages(pageInfo.getPages()); // 总页数
		pageDto.setData(orders); // 商品数据
		return pageDto;
		
	}
	@Override
	public int del(int o_id) {
	
		return orderMapper.del(o_id)>0?1:-1;
	}
	//查找卖家订单(我的卖品)
	@Override
	public PageDto<Orders> findsellerorders(int u_id,int page) {
		
		logservice.addorderLog();
		PageHelper.startPage(page,7);
		List<Orders> orders = orderMapper.findsellerorders(u_id);
		PageInfo<Orders> pageInfo = new PageInfo<>(orders);
		PageDto<Orders> pageDto = new PageDto<Orders>();
		pageDto.setCurrentPage(page);//当前页
		pageDto.setPageSize(7);//每一页大小
		pageDto.setTotal(pageInfo.getTotal());//总条数
		pageDto.setTotalPages(pageInfo.getPages()); // 总页数
		pageDto.setData(orders); // 商品数据
		return pageDto;
	}
	
	
	//通过订单id查找订单详情
		public HashMap<String, Object> findorderdetail(int orderid,int u_id) {
			//通过订单id查找订单,通过商品id查找商品详情
			Orders orders = orderMapper.findorderdetail(orderid);
			Product product = productMapper.find(orders.getP_id());
			//通过用户id查找收货地址
			List<Address> addresses = addressMapper.findAddressByUid(u_id);
			HashMap<String, Object> map = new HashMap<>();
			map.put("product", product);
			map.put("addresses", addresses);
			map.put("orders", orders);
			return map;
			
		};

}
